package com.xinlang.util;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileUtil {
	private static final int BUF_SIZE = 8192;

	private FileUtil() {
	}

	public static void mkdirs(String path) {
		File f = new File(path);
		if (!f.exists()) {
			f.mkdirs();
		}
	}

	public static void copyFile(String srcFile, String dstFile) {
		try {
			copyDirectory(new File(srcFile), new File(dstFile));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void copyDirectory(String srcPath, String dstPath) {
		try {
			copyDirectory(new File(srcPath), new File(dstPath));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	protected static void copyDirectory(File src, File dst) throws IOException {
		if (src.isDirectory()) {
			if (src.getAbsolutePath().indexOf("svn") != -1) {
				return;
			}
			if (!dst.exists()) {
				dst.mkdirs();
			}

			String files[] = src.list();
			for (int i = 0; i < files.length; i++) {
				copyDirectory(new File(src, files[i]), new File(dst, files[i]));
			}
		} else {
			if (!src.exists()) {
				throw new FileNotFoundException(src.getName()
						+ " File or directory does not exist.");
			} else {
				FileInputStream in = null;
				FileOutputStream out = null;
				try {
					in = new FileInputStream(src);
					out = new FileOutputStream(dst);

					byte[] buffer = new byte[BUF_SIZE];
					int count = 0;
					do {
						out.write(buffer, 0, count);
						count = in.read(buffer, 0, buffer.length);
					} while (count != -1);
				} finally {
					if (in != null) {
						in.close();
					}
					if (out != null) {
						out.close();
					}
				}
			}
		}
	}

	/**
	 * removeDir��delete���Apache Ant�Ĵ���
	 */
	public static void removeDir(String d) {
		removeDir(new File(d), true);
	}

	public static void removeFilesInDir(String d) {
		removeDir(new File(d), false);
	}

	public static void removeFile(String name) {
		File f = new File(name);
		f.delete();
	}

	/**
	 * deleteDָʾ�Ƿ�ɾ��File d
	 */
	protected static void removeDir(File d, boolean deleteD) {
		String[] list = d.list();
		if (list == null) {
			list = new String[0];
		}
		for (int i = 0; i < list.length; i++) {
			String s = list[i];
			File f = new File(d, s);
			if (f.isDirectory()) {
				removeDir(f, deleteD);
			} else {
				if (!delete(f)) {
					System.err.println("Unable to delete file " + f.getAbsolutePath());
				}
			}
		}
		if (deleteD) {
			if (!delete(d)) {
				System.err.println("Unable to delete directory " + d.getAbsolutePath());
			}
		}
	}

	private static boolean delete(File f) {
		if (!f.delete()) {
			if (Os.isFamily("windows")) {
				System.gc();
			}
			try {
				Thread.sleep(10/* DELETE_RETRY_SLEEP_MILLIS */);
			} catch (InterruptedException ex) {
				// Ignore Exception
			}

			if (!f.delete()) {
				return false;
			}
		}
		return true;
	}
}
